import hljs from 'highlight.js'
import MarkdownIt from 'markdown-it'
import type { Options } from 'markdown-it'
import mdKatex from '@vscode/markdown-it-katex'
import markdownItMathJax from 'markdown-it-math'
import { codePlugin } from './codePlugin/codePlugin'
import { aPlugin } from './aPlugin'
import { docQuotePlugin } from './docLInk'
import { customLinkPlugin } from './customLink'

interface OptionsIn extends Partial<Options> {
    lineNumbers?: boolean
}

export function createMarkdown(options: OptionsIn) {
    const md: any = new MarkdownIt({
        ...options,
        // html: true,
        // breaks: true,
        // linkify: true,
        // typographer: true,
        langPrefix: 'language-',
        highlight: function (str: any, lang: any): string {
            if (lang && hljs.getLanguage(lang)) {
                try {
                    return hljs.highlight(str, { language: lang, ignoreIllegals: true }).value
                } catch { /* empty */ }
            }
            try {
                return hljs.highlightAuto(str).value
            } catch { /* empty */ }
            return ''
        }
    })

    md.use(codePlugin)

    md.use(mdKatex, {
        output: 'mathml'
    })

    md.use(markdownItMathJax, {
        inline: true,
        validate: false,
        inlineOpen: '$',
        inlineClose: '$'
    })

    md.use(aPlugin).use(docQuotePlugin).use(customLinkPlugin)

    return md
}

export const preprocessContent = (content: string) => {
    return content
        .replace(/\\\(/g, '$$')   // 将 \( 替换为 $
        .replace(/\\\)/g, '$$')   // 将 \) 替换为 $
        .replace(/\\]/g, '$$$')   // 将 \] 替换为 $$
        .replace(/\\\[/g, '$$$')  // 将 \[ 替换为 $$
}
